# api/audit.py
from flask import Blueprint, request, jsonify
from models.audit import AuditLog
from utils.auth import require_authentication, require_role
from app import db

audit_bp = Blueprint('audit', __name__, url_prefix='/api/audit')

@audit_bp.route('/logs', methods=['GET'])
@require_authentication
@require_role("ADMIN")
def get_audit_logs(current_user):
    """获取审计日志（仅管理员可访问）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 50, type=int)
        event_type = request.args.get('event_type')
        object_type = request.args.get('object_type')
        object_id = request.args.get('object_id')
        
        query = AuditLog.query
        
        if event_type:
            query = query.filter_by(event_type=event_type)
        if object_type:
            query = query.filter_by(object_type=object_type)
        if object_id:
            query = query.filter_by(object_id=object_id)
        
        logs = query.order_by(AuditLog.timestamp.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        log_list = []
        for log in logs.items:
            log_list.append({
                'id': log.id,
                'user_id': log.user_id,
                'event_type': log.event_type,
                'object_type': log.object_type,
                'object_id': log.object_id,
                'data': log.data,
                'old_data': log.old_data,
                'timestamp': log.timestamp.isoformat()
            })
        
        return jsonify({
            'status': 'success',
            'total': logs.total,
            'pages': logs.pages,
            'current_page': logs.page,
            'logs': log_list
        }), 200
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'Failed to get audit logs: {str(e)}'
        }), 500